<!--<template>-->

<!--</template>-->

<!--<script>-->
<!--export default {-->
<!--  name: 'BookTest'-->
<!--}-->
<!--</script>-->

<!--<style scoped>-->

<!--</style>-->
<!--<template>-->

<!--</template>-->

<!--<script>-->
<!--export default {-->
<!--  name: 'TestADU'-->
<!--}-->
<!--</script>-->

<!--<style scoped>-->

<!--</style>-->

<template>
  <div>
<!--    <img :src="src1">-->
    <div style="text-align:left">
      <!-- <el-input v-model="tableDataName" size="small" placeholder="请输入姓名" style="width:240px"></el-input>
      <el-button type="primary" size="small" @click="searchUser">搜索</el-button> -->
      <!-- <el-button type="primary" size="small" @click="openData">展示数据</el-button> -->
      <el-button type="success" size="small" @click="addRow(book)">新增</el-button>
      <!-- <el-button type="success" size="small" @click="handleAdd()">新增</el-button> -->
      <el-button type="primary" size="small" @click="removebook()">批量删除</el-button>
<!--      <el-input  placeholder="请输入内容"  style="width: 12%;position: absolute;left: 60%"></el-input>-->
<!--      <el-button type="primary" icon="el-icon-search"  style="margin-left: 62.2%;height: 95%;display: inline-block">搜索</el-button>-->
    </div>
    <div>
      <el-table :data="book.slice((currentPage-1)*pageSize,currentPage*pageSize)" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
        <el-table-column type="selection" width="60">
        </el-table-column>
        <el-table-column type="index" width="30">
        </el-table-column>
        <el-table-column prop="id"  label="编号" width="30" sortable>
        </el-table-column>
        <el-table-column prop="name"  label="图书名称" width="110" sortable>
        </el-table-column>
        <el-table-column prop="tyname"  label="类型" width="40" sortable>
        </el-table-column>
        <el-table-column prop="tename"  label="纸质" width="70" sortable>
        </el-table-column>
        <el-table-column prop="puname"  label="出版社" width="80" sortable>
        </el-table-column>
        <el-table-column prop="brname"  label="发行商" width="30" sortable>
        </el-table-column>
        <el-table-column prop="auname"  label="作者" width="70" sortable>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="60" sortable>
        </el-table-column>
        <el-table-column prop="head"  label="封面" width="100" sortable>
          <template   slot-scope="scope">
            <img :src="scope.row.head"  min-width="70" height="70" />
          </template>
        </el-table-column>
        <el-table-column prop="date" label="出版日期" min-width="100" sortable>
        </el-table-column>
        <el-table-column prop="brief" label="书籍详情" min-width="180" sortable  :formatter="stateFormat">
        </el-table-column>
        <el-table-column prop="detail"  label="创作背景" width="180" sortable  :formatter="stateFormat">
        </el-table-column>
        <el-table-column prop="state"  label="发行状态" width="50" sortable>
          <template   slot-scope="scope">
            <span v-if="scope.row.state===1" style="color:hotpink">已发行</span>
            <span v-if="scope.row.state===0">未发行</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="390">
          <template slot-scope="scope">
            <!-- <el-button type="success" size="small" @click="handleEdit(scope.$index, scope.row)">新增</el-button> -->
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination align='center'
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[1,5,10,20]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="book.length">
      </el-pagination>
    </div>
    <!--新增/编辑界面-->
    <el-dialog :title="titleMap[dialogStatus]" :visible.sync="FormVisible" :close-on-click-modal="false" class="edit-form"
               :before-close="handleClose">
      <el-form :model="Formb" label-width="80px" :rules="editFormRules" ref="Form">
        <el-form-item label="图书编号" prop="id" hidden>
          <el-input v-model="Formb.id" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="图书名称" prop="name">
          <el-input v-model="Formb.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="图书类型" style="display:inline-block">
          <!--          <el-input type="select" v-model="Form.state"></el-input>-->
          <el-select v-model="Formb.type" placeholder="请选择"  value-key="tid">
            <el-option
              v-for="item in FormType"
              :key="item.tid"
              :label="item.name"
              :value="item.tid">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="纸张类型" style="display:inline-block">
          <!--          <el-input type="select" v-model="Form.state"></el-input>-->
          <el-select v-model="Formb.texture" placeholder="请选择"  value-key="id">
            <el-option
              v-for="item in FormTexture"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出版社" style="display:inline-block">
          <!--          <el-input type="select" v-model="Form.state"></el-input>-->
          <el-select v-model="Formb.publisher" placeholder="请选择"  value-key="id">
            <el-option
              v-for="item in FormPublisher"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图书品牌" style="display:inline-block">
          <!--          <el-input type="select" v-model="Form.state"></el-input>-->
          <el-select v-model="Formb.brand" placeholder="请选择"  value-key="id">
            <el-option
              v-for="item in FormBrand"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="作者" style="display:inline-block;margin-left: -6%">
          <!--          <el-input type="select" v-model="Form.state"></el-input>-->
          <el-select v-model="Formb.author" placeholder="请选择"  value-key="id">
            <el-option
              v-for="item in FormAuthor"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图书价格" style="display:inline-block">
          <el-input-number v-model="Formb.price"></el-input-number>
        </el-form-item>
<!--        <el-form-item label="图书封面" prop="name">-->
<!--          <el-input v-model="Form.head" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->

<!--        <el-form-item prop="image">-->
<!--          <span>图片：</span>-->
<!--          <el-input v-if="false" v-model="addForm.image" />-->
<!--          &lt;!&ndash;elementui的上传图片的upload组件&ndash;&gt;-->
<!--          <el-upload-->
<!--            ref="upload"-->
<!--            :show-file-list="false"-->
<!--            class="upload-demo"-->
<!--            action=""-->
<!--            :limit="1"-->
<!--            :multiple="true"-->
<!--            :before-upload="beforeupload"-->
<!--            :auto-upload="false"-->
<!--            :on-change="handleChange"-->
<!--            :data="addForm"-->
<!--          >-->
<!--            <el-button size="small" type="primary">点击上传</el-button>-->
<!--            <img v-if="addForm.image" :src="addForm.image" alt="" style="width:50%; height:50%;">-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
        <el-form-item prop="image">
          <span>图片：</span>  <div class="file">
          <input type="file" class="updata" accept="image/*" @change="change($event)" ref="updata">
          <img :src="imageUrl ? imageUrl : baseImg" alt="" class="img">
        </div>
        </el-form-item>

        <el-form-item label="选择日期" :picker-options="pickerOptions">
          <div>
            <el-date-picker v-model="Formb.date" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
                            value-format="yyyy-MM-dd"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="图书详情">
          <el-input v-model="Formb.brief" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="创作背景" >
          <el-input type="textarea" v-model="Formb.detail"></el-input>
        </el-form-item>
        <el-form-item label="发行状态" >
<!--          <el-input type="select" v-model="Form.state"></el-input>-->
          <el-select v-model="Formb.state" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCancel('Formb')">取消</el-button>
        <el-button v-if="addBtnshow" type="primary" @click.native="confirmAdd('Formb')">确定</el-button>
        <el-button v-if="editBtnshow" type="primary" @click.native="confirmEdit('Formb')">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
var _index;
import qs from 'qs'
export default {
  name: 'TestADU',
  data () {
    return {

      // 上传的图片
      imageUrl: '',


      // 默认的图片
      baseImg: '',
      addForm: {
        image: ''
      },
      rules: {
        image: [
          {required: true, message: '请上传图片', trigger: 'blur'}
        ]
      },

      src1: require('../../assets/微信图片_20210731215732.jpg'),

      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now();
        }
      },

      options: [{
        value: '1',
        label: '已发行'
      }, {
        value: '0',
        label: '未发行'
      }],

      currentPage: 1,
      pageSize: 5,
      titleMap: {
        addEquipment: '新增',
        editEquipment: "编辑"
      },
      //新增和编辑弹框标题
      // dialogStatus: "",
      Formb: {
        id: '',
        name: '',
        type: '',
        texture: '',
        publisher: '',
        brand: '',
        author: '',
        price: 0,
        head: '',
        detail: '',
        date: '',
        state: '',
        tyname: '', brname: '', tename: '', puname: '', auname: ''
      },

      book: [],

      FormType: {
        tid: '',
        name: '',
      },
      FormTexture: {
        id: '',
        name: '',
      },
      FormBrand: {
        id: '',
        name: '',
      },
      FormPublisher: {
        id: '',
        name: '',
      },
      FormAuthor: {
        id: '',
        name: '',
      },

      editFormRules: {
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        reserve: [
          {required: true, message: '请输入商品库存', trigger: 'blur'}
        ],
        desc: [
          {required: true, message: '请输入商品描述', trigger: 'blur'}
        ],
      },
      FormVisible: false,
      currentRow: [],
      ids: [],
      listLoading: '',
      addBtnshow: false,
      editBtnshow: false,
      editLoading: '',
      dialogStatus: '',
      selected: [],
      editid: '',
      searchForm: []
    }
  },
  created () {
    // 获取默认显示的图片
    this.baseImg = require('../../assets/logo.png')

    this.$http.post('/book/select3').then(data => {
      console.log(data);
      this.book = data;
    });

    this.$http.post('/type/select').then(data => {
      console.log(data);
      this.FormType = data;
      //alert(this.FormType);
    });
    this.$http.post('/brand/select').then(data => {
      console.log(data);
      this.FormBrand = data;
      //alert(this.FormType);
    });
    this.$http.post('/author/select').then(data => {
      console.log(data);
      this.FormAuthor = data;
      //alert(this.FormType);
    });
    this.$http.post('/publisher/select').then(data => {
      console.log(data);
      this.FormPublisher = data;
      //alert(this.FormType);
    })
    this.$http.post('/texture/select').then(data => {
      console.log(data);
      this.FormTexture = data;
      //alert(this.FormType);
    });

  },
  methods: {
    handleChange (file, fileList) {
      this.addForm.image = URL.createObjectURL(file.raw)
      // var files = this.addForm.image
      // files.push(this.addForm.image)
    },
    beforeupload (file) {
      return true
    },
    submitForms (addForm) { // 新增表单提交
      this.axios({
        method: 'post',
        url: 'url',
        headers: {Authorization: window.sessionStorage.getItem('token')},
        data: {}
      })
        .then(res => {
          this.$refs[addForm].validate((valid) => {
            if (valid) {
              this.$refs.upload.submit()
              // 不可缺少
            } else {
              console.log('error submit!!')
              return false
            }
          })
        })
        .catch(function (error) {
          console.log(error)
        })
    },

    selsChange: function (val) {  //点击选中
      console.log(val);
      this.selected = val;
    },
    // 点击新增
    addRow (book, event) {
      this.FormVisible = true;
      this.Form = {
        id: 0,
        name: '',
        price: 0,
        date: '',
      };

      this.dialogStatus = "addEquipment"
      this.addBtnshow = true
      this.editBtnshow = false

    },
    // 点击确定（新增）
    confirmAdd () {

      // this.book.push({
      //   name: this.Form.name,
      //   price: this.Form.price,
      //   reserve: this.Form.reserve,
      //   data: this.Form.data,
      //   desc: this.Form.desc
      // })
      console.log("这是fb"+this.Formb.name)
      this.$http.post("/book/insert",this.Formb).then(add => {
        //alert(add);
        if (add > 0) {
          alert("添加成功");
          window.location.reload();
        } else {
          alert("添加失败")
        }
      })
     // this.FormVisible = false;
    },
    //点击编辑
    handleEdit: function (index, row) {
      this.FormVisible = true;
      this.Formb = Object.assign({}, row); //这句是关键！！！
      _index = index;
      console.log(index);
      console.log(_index);

      this.dialogStatus = "editEquipment"
      this.addBtnshow = false
      this.editBtnshow = true
    },
    // 点击确定（编辑）
    confirmEdit () {
      this.$http.post("/book/update", this.Formb).then(add => {
        if (add > 0) {
          alert("修改成功");
          window.location.reload();
        } else {
          alert("修改失败")
        }
      });

    },
    //点击关闭dialog
    handleClose (done) {
      //  done();
      //  location.reload();
      this.FormVisible = false;
    },
    //点击取消
    handleCancel (formName) {
      this.FormVisible = false;
    },
    // 删除
    handleDelete (index, rows) {

      // console.log(index, row);
      this.Form.id = rows
      // alert(this.Form.id);
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post("/book/delete", this.Formb).then(add => {
          if (add > 0) {
            type: 'success';
            message: '删除成功!';
            window.location.reload();
          } else {
            alert("修改失败")
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    removebook () {
      this.$confirm('此操作将永久删除 ' + this.selected.length + ' 条数据, 是否继续?', '提示', {type: 'warning'})
        .then(() => {
          console.log(this.selected);
          var ids = [];
          //提取选中项的id
          $.each(this.selected, (i, book) => {
            ids.push(book.id);
          });
          // 向请求服务端删除
          //  var resource = this.$resource(this.url);
          resource.remove({ids: ids.join(",")})
            .then((response) => {
              this.$message.success('删除了' + this.selected.length + '个用户!');
              this.getbook();
            })
            .catch((response) => {
              this.$message.error('删除失败!');
            });
        })
        .catch(() => {
          this.$Message('已取消操作!');
        });
    },

    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    stateFormat (row, column, cellValue) {
      // console.log(row , column , cellValue)
      if (!cellValue) return "";
      if (cellValue.length > 40) {
        //最长固定显示4个字符
        return cellValue.slice(0, 40) + "...";
      }
      return cellValue;
    },
    clickContent: function (row, column, cell, event) {
      clickContent(row, column, cell, event)
      {
        if (column.label === '数据内容') {  // 只有点击数据内容列时才会展开
          row.flag = !row.flag  // 这个参数是当时将数据存储到表格中时特意加上控制表格的展开和省略的
        }
      }
    },

    change (e) {
      console.log(e.target.files[0].name);
      // 判断是不是规定格式
      // let name  =  e.target.files[0].name

      // 获取到第一张图片
      let file = e.target.files[0]

      // 创建文件读取对象
      var reader = new FileReader()
      var that = this

      //  将文件读取为DataURL
      reader.readAsDataURL(file)

      // 读取成功调用方法
      reader.onload = e => {
        console.log('读取成功');

        // e.target.result 获取 读取成功后的  文件DataURL
        that.imageUrl = e.target.result

        // 如果要将图片上传服务器，就在这里调用后台方法
      }

    }
  },



  mounted () {

  },


}
</script>
<style>
/*.file {*/
/*  position: relative;*/
/*  width: 200px;*/
/*  height: 150px;*/
/*  background-color: #ccc;*/
/*}*/
/*.updata {*/
/*  display: block;*/
/*  height: 100%;*/
/*  width: 100%;*/
/*  opacity: 0;*/
/*  position: absolute;*/
/*  top: 0;*/
/*  left: 0;*/
/*  z-index: 10;*/
/*}*/
/*.img {*/
/*  position: absolute;*/
/*  top: 0;*/
/*  left: 0;*/
/*  width: 200px;*/
/*  height: 150px;*/
/*}*/
</style>
